//
//  BCAPIBaseRequest.m
//  GSBlockChain
//
//  Created by guoshikeji_a on 2018/11/29.
//  Copyright © 2018 guoshikeji. All rights reserved.
//

#import "BCAPIBaseRequest.h"

//
#import "BCAPIBaseResponse.h"

@implementation BCAPIBaseRequest

- (NSString *)absoluteUrl {
    return [NSString stringWithFormat:@"%@/%@",MainHost,self.relativelyUrl];
}


- (NSString *)getSign {
    id obj = [self yy_modelToJSONObject];
    if ([obj isKindOfClass:[NSDictionary class]]) {
        NSDictionary *dic = obj;
        NSArray *allKeys = dic.allKeys;
        if (!allKeys.count) {
            return nil;
        }
        //对所有有效请求参数按照key做逆向排序
        NSArray *myary = [allKeys sortedArrayUsingComparator:^(NSString * obj1, NSString * obj2){
            return (NSComparisonResult)[obj2 compare:obj1 options:NSNumericSearch];
        }];
        //
        NSMutableArray *array = [NSMutableArray arrayWithCapacity:myary.count];
        for(int i=0; i<myary.count; i++) {
            NSString *key = myary[i];
            id value = dic[key];
            if ([value isKindOfClass:NSString.class]) {
                //对value进行urlencode编码
                NSString *urlEncodeValue = [self urlEncode:value usingEncoding:NSUTF8StringEncoding];
                //
                [array addObject:[NSString stringWithFormat:@"%@%@",key,urlEncodeValue]];
            }
        }
        //赋值请求时间戳
        self._timestamp = [NSString stringWithFormat:@"%.0f",[[NSDate date] timeIntervalSince1970]+1];
        //
        [array addObject:[NSString stringWithFormat:@"%@%@",NSStringFromSelector(@selector(_timestamp)),self._timestamp]];
        [array addObject:[NSString stringWithFormat:@"%@%@",NSStringFromSelector(@selector(app_id)),self.app_id]];
        
        NSString *signString = [array componentsJoinedByString:@""];
        NSString *signStringMd5 = [signString md532];
        return signStringMd5.uppercaseString;
    }
    return nil;
}

- (NSString *)urlEncode:(NSString *)string usingEncoding:(NSStringEncoding)encoding
{
    return (NSString *)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(
                                                                                 NULL,
                                                                                 (__bridge CFStringRef)string,
                                                                                 NULL,
                                                                                 (CFStringRef)@"!*'\"();:@&=+$,/?%#[]% ",
                                                                                 CFStringConvertNSStringEncodingToEncoding(encoding)));
}

- (void)getSignString {
    NSString *sign = [self getSign];
    self.sign = sign;
}


- (void)requestServer {
    if ([self requestMethod]!=GET) {//不是get请求都需要加密
        [self getSignString];
    }
    [super requestServer];
}




#pragma mark -

- (BOOL)success:(NSURLSessionDataTask *)task data:(id)obj {
    BOOL success = [super success:task data:obj];
    if (success) {
        BCAPIBaseResponse *resp = [BCAPIBaseResponse yy_modelWithJSON:obj];
        switch (resp.ret) {
            case 200://success 有数据
            case 201://success 没数据
            {
                return true;
            }
                break;
            //error
            case 401001://没有权限，请登陆
            case 401002://限制用户登陆
            case 401003://用户登陆已过期
            case 401004://未注册用户信息
            {//需要提示用户重新登录
                if (!resp.msg) {
                    resp.msg = BCLocalizedFormatString(@"Request failed: %@",@(resp.ret));
                }
                NSError *error = [NSError errorWithDomain:resp.msg code:resp.ret userInfo:nil];
                //
                [[BCUserManager sharedUser] clearLoginUser];
                [[NSNotificationCenter defaultCenter] postNotificationName:BCUserManagerUserLoginOverdueNotification object:error];
            }
            default:
            {
                if (!resp.msg) {
                    resp.msg = BCLocalizedFormatString(@"Request failed: %@",@(resp.ret));
                }
                
                NSError *error = [NSError errorWithDomain:resp.msg code:resp.ret userInfo:nil];
                if (self.requestFailed) {
                    self.requestFailed(error);
                }
                return false;
            }
                break;
        }
    }
    return success;
}


@end
